package com.bootx.officialAccount.service.impl;

import com.bootx.officialAccount.entity.AccessToken;
import com.bootx.officialAccount.entity.OfficialAccount;
import com.bootx.officialAccount.service.AccessTokenService;
import com.bootx.officialAccount.util.OfficialAccountUtils;
import com.bootx.service.impl.BaseServiceImpl;
import com.bootx.util.DateUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author black
 */
@Service
public class AccessTokenServiceImpl extends BaseServiceImpl<AccessToken,Long> implements AccessTokenService {

    @Override
    public boolean expire(OfficialAccount officialAccount) {
        Long l = jdbcTemplate.queryForObject("select count(id) from accesstoken where expiresDate>NOW() and officialAccount_id=?", Long.class, officialAccount.getId());
        if (l==null){
            return true;
        }
        return l <= 0;
    }

    @Override
    public AccessToken createOrUpdate(OfficialAccount officialAccount, AccessToken accessToken) {
        try {
            Long id = jdbcTemplate.queryForObject("select id from accesstoken where officialAccount_id=? order by createdDate desc limit 1", Long.class, officialAccount.getId());
            if (id!=null){
                AccessToken accessToken1 = super.find(id);
                accessToken1.setAccessToken(accessToken.getAccessToken());
                accessToken1.setExpiresIn(accessToken.getExpiresIn());
                accessToken1.setExpiresDate(DateUtils.getNextSecond(accessToken.getExpiresIn()/2));
                return super.update(accessToken1);
            }
        }catch (Exception ignored){
        }
        accessToken.setExpiresDate(DateUtils.getNextSecond(accessToken.getExpiresIn()/2));
        accessToken.setOfficialAccount(officialAccount);
        return super.save(accessToken);
    }

    @Override
    public AccessToken findByOfficialAccount(OfficialAccount officialAccount) {
        Long id = jdbcTemplate.queryForObject("select id from accesstoken where officialAccount_id=? order by createdDate desc limit 1", Long.class, officialAccount.getId());
        if (id==null){
            return null;
        }
        if(expire(officialAccount)){
            AccessToken accessToken = OfficialAccountUtils.getToken();
            return createOrUpdate(officialAccount, accessToken);
        }
        return super.find(id);
    }
}
